package com.hanggold;

import org.apache.catalina.Context;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * https://www.codejava.net/servers/tomcat/how-to-embed-tomcat-server-into-java-web-applications
 *
 * https://devcenter.heroku.com/articles/create-a-java-web-application-using-embedded-tomcat
 *
 * @author <a href="mailto:sunmch@163.com">smc</a>
 * @date 2019-07-18 15:03
 * @since
 **/
public class MainDemo {

    public static void main(String[] args) throws Exception {

//        String webappDirLocation = "src/main/webapp/";
        Tomcat tomcat = new Tomcat();

        //The port that we should run on can be set into an environment variable
        //Look for that variable and default to 8080 if it isn't there.
        String webPort = System.getenv("PORT");
        if(webPort == null || webPort.isEmpty()) {
            webPort = "8080";
        }

        tomcat.setPort(Integer.valueOf(webPort));

        String docBase = new File(".").getAbsolutePath();


        Context context = tomcat.addContext("/api",docBase);

        HttpServlet servlet = new HttpServlet() {
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                    throws ServletException, IOException {
                PrintWriter writer = resp.getWriter();

                writer.println("<html><title>Welcome</title><body>");
                writer.println("<h1>Have a Great Day!</h1>");
                writer.println("</body></html>");
            }
        };

        String servletName = "Servlet1";
        String urlPattern = "/go";

        tomcat.addServlet("/", servletName, servlet);
        context.addServletMappingDecoded(urlPattern, servletName);




//        StandardContext ctx = (StandardContext) tomcat.addWebapp("/", new File(".").getAbsolutePath());
//
//
//        System.out.println("nwe: "+ new File(".").getAbsolutePath());
//        // Declare an alternative location for your "WEB-INF/classes" dir
//        // Servlet 3.0 annotation will work
//        File additionWebInfClasses = new File("servlet/target/classes");
//        WebResourceRoot resources = new StandardRoot(ctx);
//        resources.addPreResources(new DirResourceSet(resources, ".",
//                additionWebInfClasses.getAbsolutePath(), "/"));
//        ctx.setResources(resources);

        tomcat.start();
        tomcat.getServer().await();







    }

}
